#include "StdAfx.h"
#include "MICEXTable.h"

MICEXTable::MICEXTable(void)
{
}

MICEXTable::~MICEXTable(void)
{
}

void MICEXTable::ClearTableData()
{
	if(!TableKeys.empty())
	{
		TableKeys.clear();
	}

	for(TABLEDATAVECTOR::iterator dataIterator = TableData.begin(); dataIterator != TableData.end(); dataIterator++) 
	{
		if(*dataIterator != 0)
			delete [] *dataIterator;
	}
	TableData.clear();
}

void MICEXTable::UpdateTableRow(int nFields, BYTE* pFieldBuf, int32 nDataLen, BYTE* pDataBuf)
{
	MICEXTableKey key(this, nFields, pFieldBuf, nDataLen, pDataBuf);

	TABLEKEYMAPTOPOSITION::const_iterator keyIterator = TableKeys.find(key);

	LPBYTE pRowData;

	if (keyIterator != TableKeys.end())
	{
		//Row update
		//We found row position
		pRowData = TableData.at(keyIterator->second);
	}
	else
	{
		//New row
		pRowData = new BYTE[RowDataSize];
		memset(pRowData, ' ', RowDataSize);
		
		TableData.push_back(pRowData);
		TableKeys[key] = TableData.size() - 1;
	}

	BYTE* pDataBufPtr = pDataBuf;
	int32 nRealFields = (nFields != 0) ? nFields : OutputFieldsCount;
	
	for(int32 nFieldsCnt = 0; nFieldsCnt < nRealFields; nFieldsCnt++) 
	{
		int32 nFieldNum;
		if(pFieldBuf != 0)
			nFieldNum = pFieldBuf[nFieldsCnt];
		else
			nFieldNum = nFieldsCnt;

		if(nFieldNum < OutputFieldsCount) 
		{
			BYTE* pFieldVal = pDataBufPtr;
			SetFieldValue(nFieldNum, pRowData, pFieldVal);
			pDataBufPtr += OutputFields[nFieldNum].FieldSize;
		}
	}
}